<template>
  <div class="page">
    <div class="topSearch">
      <div class="title">
        <span
          style="
            width: 3px;
            height: 20px;
            background-color: #0f79e2;
            margin-right: 8px;
          "
        ></span
        ><span>单品出库</span>
      </div>
      <div class="search">
        <span>单名：</span>
        <el-input
          size="small"
          clearable
          style="width: 200px"
          v-model="singleName"
          placeholder="请输入采购单名"
        ></el-input>
        <span>店铺名称：</span>
        <el-input
          size="small"
          clearable
          style="width: 200px"
          v-model="storeName"
          placeholder="请输入店铺名称"
        ></el-input>
        <span>所属仓库：</span>
        <el-select
          clearable
          v-model="areaId"
          size="small"
          style="width: 200px"
          placeholder="请选择"
        >
          <el-option
            v-for="item in warehouseList"
            :key="item.area"
            :label="item.areaName"
            :value="item.area"
          />
        </el-select>
        <span>选择日期：</span>
        <el-date-picker
          v-model="sateValue"
          type="daterange"
          range-separator="至"
          clearable
          size="small"
          @change="selectTime"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
        <el-button
          size="small"
          type="primary"
          style="width: 80px; margin-left: 20px"
          @click="getOutportList"
          >查询
        </el-button>
        <el-button
          size="small"
          style="width: 80px; margin-left: 20px"
          @click="reset"
          >重置
        </el-button>
        <el-button
          size="small"
          type="primary"
          style="width: 100px; position: absolute; right: 40px"
          @click="addProduct"
          >新增出库单
        </el-button>
      </div>
    </div>
    <div class="centerTable">
      <el-table
        :data="purchaseData"
        border
        height="calc(100vh - 350px)"
        :cellStyle="{ textAlign: 'center', 'font-size': '12px' }"
        v-loading="loading"
        :headerCellStyle="{
          textAlign: 'center',
          fontWeight: 400,
          background: '#66b1ff',
          color: 'white',
        }"
      >
        <el-table-column prop="singleNo" label="单号" width="150px" />

        <el-table-column prop="singleName" label="单名" />
        <el-table-column prop="storeName" label="店铺名称" />
        <el-table-column label="产品明细" width="550px">
          <template slot-scope="scope">
            <el-table
              :data="scope.row.list"
              maxHeight="250px"
              :cellStyle="{ textAlign: 'center', 'font-size': '12px' }"
              :headerCellStyle="{
                textAlign: 'center',
                fontWeight: 400,
                background: '#66b1ff',
                color: 'white',
              }"
              border
              style="width: 100%"
            >
              <el-table-column prop="productCode" label="编码" />
              <el-table-column prop="productName" label="产品" width="200px" />
              <el-table-column prop="norms" label="规格" />
              <el-table-column prop="singleNum" label="数量" />
            </el-table>
          </template>
        </el-table-column>
        <el-table-column prop="picture" label="出库凭证">
          <template slot-scope="scope">
            <el-image
              v-for="(v, i) in scope.row.singleProof"
              :key="i"
              style="width: 50px; height: 50px"
              ref="preview"
              :src="host + v"
              :preview-src-list="[host + v]"
            >
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="picture" label="付款凭证">
          <template slot-scope="scope">
            <el-image
              v-for="(v, i) in scope.row.paymentProof"
              :key="i"
              style="width: 50px; height: 50px"
              ref="preview"
              :src="host + v"
              :preview-src-list="[host + v]"
            >
            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="所属仓库" width="190px">
          <template slot-scope="scope">
            <div
              class="warehouseTag"
              v-if="scope.row.areaId === 46"
              style="
                border: 1px solid #f5b330;
                background-color: #fef7ea;
                color: #f5b330;
              "
            >
              <img src="@/assets/svg/hubei.svg" class="warehouse_icon" /><span
                >宁乡贰</span
              >
            </div>
            <div
              class="warehouseTag"
              v-if="scope.row.areaId === 54"
              style="
                border: 1px solid #f5b330;
                background-color: #fef7ea;
                color: #f5b330;
              "
            >
              <img src="@/assets/svg/hubei.svg" class="warehouse_icon" /><span
                >武汉仓</span
              >
            </div>
            <div
              class="warehouseTag"
              v-if="scope.row.areaId === 43"
              style="
                border: 1px solid #787cfc;
                background-color: #f1f2ff;
                color: #787cfc;
              "
            >
              <img
                src="@/assets/svg/ningxiangyi.svg"
                class="warehouse_icon"
              /><span>宁乡壹</span>
            </div>
            <div
              class="warehouseTag"
              v-if="scope.row.areaId === 44"
              style="
                border: 1px solid #497ff4;
                background-color: #f1f5fe;
                color: #497ff4;
              "
            >
              <img
                src="@/assets/svg/guangdong.svg"
                class="warehouse_icon"
              /><span>广东仓</span>
            </div>
            <div
              class="warehouseTag"
              v-if="scope.row.areaId === 45"
              style="
                border: 1px solid #4dc8ee;
                background-color: #edf9fd;
                color: #4dc8ee;
              "
            >
              <img src="@/assets/svg/guangxi.svg" class="warehouse_icon" /><span
                >广西仓</span
              >
            </div>
            <div
              class="warehouseTag"
              v-if="scope.row.areaId === 55"
              style="
                border: 1px solid #4dc8ee;
                background-color: #edf9fd;
                color: #4dc8ee;
              "
            >
              <img src="@/assets/svg/guangxi.svg" class="warehouse_icon" /><span
                >西安1仓</span
              >
            </div>
            <div
              class="warehouseTag"
              v-if="scope.row.areaId === 56"
              style="
                border: 1px solid #4dc8ee;
                background-color: #edf9fd;
                color: #4dc8ee;
              "
            >
              <img src="@/assets/svg/guangxi.svg" class="warehouse_icon" /><span
                >西安2仓</span
              >
            </div><div
              class="warehouseTag"
              v-if="scope.row.areaId === 58"
              style="
                border: 1px solid #4dc8ee;
                background-color: #edf9fd;
                color: #4dc8ee;
              "
            >
              <img src="@/assets/svg/guangxi.svg" class="warehouse_icon" /><span
                >山西仓</span
              >
            </div>
            <div
              class="warehouseTag"
              v-if="scope.row.areaId === 52"
              style="
                border: 1px solid #00acf1;
                background-color: #e5f7f1;
                color: #00acf1;
              "
            >
              <img src="@/assets/svg/yunnan.svg" class="warehouse_icon" /><span
                >贵州仓</span
              >
            </div>
            <div
              class="warehouseTag"
              v-if="scope.row.areaId === 53"
              style="
                border: 1px solid #4dc8ee;
                background-color: #edf9fd;
                color: #4dc8ee;
              "
            >
              <img src="@/assets/svg/guangxi.svg" class="warehouse_icon" /><span
                >云南仓</span
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" />
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column prop="outInventory" label="是否出库">
          <template slot-scope="scope">
            <span v-if="scope.row.outInventory == 0" style="color: #2cb5e8"
              >未出库</span
            >
            <span v-if="scope.row.outInventory == 1" style="color: #ebb563"
              >已出库</span
            >
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">
            <div style="display: flex; flex-direction: column">
              <!--              <el-link-->
              <!--                v-if="scope.row.outInventory !== 1"-->
              <!--                @click="editOutport(scope.row)"-->
              <!--                style="-->
              <!--                  color: #0f79e2;-->
              <!--                  width: auto;-->
              <!--                  background-color: #e7f1fc;-->
              <!--                  cursor: pointer;-->
              <!--                  text-decoration: none;-->
              <!--                "-->
              <!--              >-->
              <!--                编辑-->
              <!--              </el-link>-->

              <el-link
                @click="outWarehouse(scope.row)"
                style="color: #ebb563; margin-left: 10px; cursor: pointer"
                v-if="scope.row.outInventory !== 1"
                >出库
              </el-link>
              <el-link @click="outportDetail(scope.row)" style="color: #409eff"
                >出库清单</el-link
              >
              <!--              <el-link-->
              <!--                @click="exportItem(scope.row)"-->
              <!--                style="-->
              <!--                  color: #0f79e2;-->
              <!--                  width: auto;-->
              <!--                   margin-top: 5px;-->
              <!--                  background-color: #e7f1fc;-->
              <!--                  cursor: pointer;-->
              <!--                  text-decoration: none;-->
              <!--                "-->
              <!--              >-->
              <!--                导出-->
              <!--              </el-link>-->
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-pagination
      style="padding: 20px 0"
      align="right"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[20, 30, 40, 50]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalCount"
    >
    </el-pagination>
    <!--    分割线--><!--    分割线--><!--    分割线--><!--    分割线--><!--    分割线--><!--    分割线--><!--    分割线-->

    <el-dialog
      :close-on-click-modal="false"
      :title="title"
      :visible.sync="addDialog"
      width="60%"
      top="10px"
      center
      :show-close="false"
      :before-close="handleClose"
    >
      <div
        style="
          width: 100%;
          display: flex;
          justify-content: center;
          margin-bottom: 30px;
        "
      >
        <el-upload
          class="upload-demo"
          drag
          v-if="addDialog"
          :headers="headers"
          accept=".xls,.XLS,.xlsx,.XLSX"
          :action="`${$apiHost}/material/singleInventory/import/execl`"
          :on-success="onSuccess"
          :on-error="onError"
          multiple
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">
            只能上传excel文件，且不超过500kb
          </div>
        </el-upload>
      </div>

      <div style="display: flex; align-items: center; margin-bottom: 30px">
        <div style="width: 80px; text-align: center">
          <span style="color: red">*</span>单名：
        </div>
        <el-input
          size="small"
          v-model="addForm.singleName"
          style="width: 36%"
        ></el-input>
        <div style="width: 80px; text-align: center; margin-left: 20px">
          <span style="color: red">*</span>创建时间：
        </div>
        <el-date-picker
          :disabled="disabled"
          v-model="addForm.createTime"
          type="date"
          size="small"
          style="width: 36%"
        >
        </el-date-picker>
      </div>
      <div style="display: flex; align-items: center; margin-bottom: 30px">
        <div style="width: 80px; text-align: center">店铺名称：</div>
        <el-select
          allow-create
          filterable
          remote
          :remote-method="inputChange"
          default-first-option
          @change="changeSaleName"
          clearable
          v-model="addForm.storeName"
          size="small"
          style="width: 36%"
          placeholder="请选择"
        >
          <el-option
            v-for="item in saleNameList"
            :key="item.orderId"
            :label="item.storeName"
            :value="item"
          >
          </el-option>
        </el-select>
        <div style="width: 80px; text-align: center; margin-left: 20px">
          <span style="color: red">*</span>出库仓库：
        </div>
        <el-select
          clearable
          v-model="addForm.areaId"
          size="small"
          :disabled="disabled"
          style="width: 36%"
          placeholder="请选择"
        >
          <el-option
            v-for="item in warehouseList"
            :key="item.area"
            :label="item.areaName"
            :value="item.area"
          />
        </el-select>
      </div>
      <div style="display: flex; align-items: center; margin-bottom: 30px">
        <div style="width: 80px; text-align: center">备注：</div>
        <el-input
          size="small"
          v-model="addForm.remark"
          style="width: 36%"
        ></el-input>
        <div style="width: 80px; text-align: center"></div>
      </div>
      <div style="display: flex; align-items: center; margin-bottom: 50px">
        <div style="width: 80px; text-align: center; margin-top: 30px">
          凭证：
        </div>
        <div>
          <span style="color: gray; font-size: 12px"
            >(粘贴复制即可上传图片)</span
          >
          <div class="div" style="display: flex; align-items: center">
            <div
              v-for="(v, i) in preSalesImg"
              style="display: flex; align-items: center; margin-right: 10px"
            >
              <el-image
                :key="i"
                style="width: 50px; height: 50px"
                ref="preview"
                :src="host + v"
                :preview-src-list="[host + v]"
              >
              </el-image>
              <div @click="deletePic(i)">
                <el-icon name="delete"></el-icon>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!--      分割线-->
      <el-table
        :data="factoryInventoryData"
        border
        max-height="300px"
        :cellStyle="{ textAlign: 'center', 'font-size': '12px' }"
        :headerCellStyle="{
          textAlign: 'center',
          fontWeight: 400,
          background: '#66b1ff',
          color: 'white',
        }"
      >
        <el-table-column prop="productName" label="产品名称" />
        <el-table-column prop="productCode" label="产品编码" />
        <el-table-column prop="norms" label="规格" />
        <el-table-column prop="singleNum" label="出库数量" />
        <!--        <el-table-column label="出库数量">-->
        <!--          <template slot-scope="scope">-->
        <!--            <el-input-number-->
        <!--                :min="0"-->
        <!--                v-model="scope.row.singleNum"-->
        <!--                @change="countChange"-->
        <!--                size="small"-->
        <!--            ></el-input-number>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialog = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="positionDetail" title="明细" center width="80%">
      <el-button type="primary" @click="exportDetail" style="float: right"
        >导出</el-button
      >
      <el-table :data="warehousePositionDetail" border center>
        <el-table-column prop="id" label="id"></el-table-column>
        <el-table-column prop="productCode" label="产品编码"></el-table-column>
        <el-table-column prop="productName" label="产品名称"></el-table-column>
        <!--        <el-table-column prop="warehousePosition" label="库位及数量"></el-table-column>-->
      </el-table>
    </el-dialog>
    <el-dialog
      :visible.sync="outDialog"
      center
      top="50px"
      width="30%"
      title="出库"
    >
      <span>付款凭证：复制粘贴即可上传图片</span>
      <div class="div" style="display: flex; align-items: center">
        <div
          v-for="(v, i) in preSalesImg"
          style="display: flex; align-items: center; margin-right: 10px"
        >
          <el-image
            :key="i"
            style="width: 50px; height: 50px"
            ref="preview"
            :src="host + v"
            :preview-src-list="[host + v]"
          >
          </el-image>
          <div @click="deletePic(i)">
            <el-icon name="delete"></el-icon>
          </div>
        </div>
      </div>
      <span slot="footer">
        <el-button @click="outDialog = false">取 消</el-button>
        <el-button @click="optionPutInventory(outInfo)" type="primary"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import Decimal from 'decimal.js'
import dayjs from 'dayjs'
import * as XLSX from 'xlsx-js-style'
import store from '../../store'

export default {
  data() {
    return {
      pageSize: 20,
      currentPage: 1,
      pageNumber: 1,
      singleName: '',
      factoryId: '',
      optionType: '',
      areaId: '',
      title: '',
      disabled: false,
      outDialog: false,
      startTime: '',
      endTime: '',
      productCode: '',
      storeName: '',
      productId: '',
      totalCount: 0,
      host: this.$imgHost,
      warehouseId: '',
      factoryName: '',
      sateValue: '',
      editSingleId: '',
      outInfo: '',
      loading: false,
      allCount: '',
      addDialog: false,
      addForm: {},
      warehouseList: [],
      preSalesImg: [],
      preSalesImgList: [],
      warehousePositionDetail: [],
      positionDetail: false,
      previewImg: [],
      saleNameList: [],
      factoryList: [],
      purchaseData: [],
      factoryInventoryData: [],
      areaList: [],
    }
  },
  computed: {
    headers() {
      return {
        token: this.token || window.$quinn.getStorage('token'),
      }
    },
  },
  created() {
    document.addEventListener('paste', this.handlePaste)
    const params = {
      pageSize: 100000,
      pageNumber: 1,
    }
    this.$api.areaLedgerAreaList(params).then((res) => {
      this.warehouseList = res
    })
    this.$api.areaLedgerAreaList().then((res) => {
      this.areaList = res
    })
    this.$api.factoryGetFactoryList().then((res) => {
      this.factoryList = res
    })
    this.getOutportList()
  },
  methods: {
    outWarehouse(val) {
      this.outInfo = val
      this.preSalesImg = this.$options.data.call(this).preSalesImg
      this.outDialog = true
    },
    inputChange(val) {
      if (val) {
        const params = {
          storeName: val,
        }
        this.$api.orderGetOrderInfoLikeName(params).then((res) => {
          this.saleNameList = res
        })
      }
    },
    changeSaleName(item) {
      this.addForm.storeName = item.storeName || item
    },
    onSuccess(res) {
      if (res) {
        this.factoryInventoryData = res.result
        this.addForm.areaId = res.result[0].areaId
        this.$message('导入成功')
      }
    },
    onError() {
      this.$message.warning('请重新导入')
    },
    exportItem(val) {
      try {
        const data = val.list.map((a) => ({
          编码: a.productCode,
          产品: a.productName,
          规格: a.norms,
          数量: a.singleNum,
        }))
        const sheetName = val.singleName + '产品明细'
        const wb = XLSX.utils.book_new()
        const sheet = XLSX.utils.json_to_sheet(data)
        sheet['!cols'] = [
          { wpx: 100 }, // 编码
          { wpx: 200 }, // 产品
          { wpx: 100 }, // 规格
          { wpx: 100 }, // 数量
        ]
        XLSX.utils.book_append_sheet(wb, sheet, sheetName)
        const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' })
        const blob = new Blob([s2ab(wbout)], {
          type: 'application/octet-stream',
        })
        const link = document.createElement('a')
        link.href = URL.createObjectURL(blob)
        link.download = `${val.singleName}产品明细${new Date().getTime()}.xlsx`
        link.click()
        URL.revokeObjectURL(link.href)
      } catch (error) {
        console.error('Error generating inventory report:', error)
      }

      function s2ab(s) {
        const buf = new ArrayBuffer(s.length)
        const view = new Uint8Array(buf)
        for (let i = 0; i < s.length; ++i) {
          view[i] = s.charCodeAt(i) & 0xff
        }
        return buf
      }
    },
    handleChange(val) {},
    handleClose() {},
    changeFactoryInventory(val) {
      this.$api.inventoryGetInventoryGoodsList({ areaId: val }).then((res) => {
        if (res) {
          res.forEach((el) => {
            el.singleNum = 0
          })
        }
        this.factoryInventoryData = res
      })
    },
    selectTime(val) {
      if (val) {
        this.startTime = dayjs(val[0]).format('YYYY-MM-DD')
        this.endTime = dayjs(val[1]).format('YYYY-MM-DD')
      } else {
        this.startTime = ''
        this.endTime = ''
      }
    },
    //操作入库
    optionPutInventory(val) {
      const data = {
        singleNo: val.singleNo,
        areaId: val.areaId,
        paymentProof: this.preSalesImg,
      }
      this.$api.singleSingleOutInventory(data).then((res) => {
        if (res === 1) {
          this.$message({ message: '操作成功', type: 'success' })
          this.outDialog = false
          this.getOutportList()
        }
      })
    },
    //单品出库列表
    getOutportList() {
      this.loading = true
      const data = {
        pageSize: this.pageSize,
        pageNumber: this.pageNumber,
        areaId: this.areaId,
        storeName: this.storeName,
        singleName: this.singleName,
        startTime: this.startTime,
        endTime: this.endTime,
      }
      this.$api.singleGetSingleList(data).then((res) => {
        res.data.forEach((el) => {
          if (el.singleProofStr) {
            // el.purchaseProofList = el.purchaseProof.split(',')
            el.singleProof.forEach((val) => {
              this.previewImg.push('https://' + val)
            })
          } else {
            // el.purchaseProofList = [el.purchaseProof]
            // el.purchaseProofList.forEach(val => {
            //   this.previewImg.push('https://' + val)
            // })
          }
        })
        this.loading = false
        this.purchaseData = res.data
        this.totalCount = res.total
      })
    },
    submit() {
      if (!this.addForm.singleName || !this.addForm.areaId) {
        return this.$message({ message: '请检查必填项！' })
      }
      this.addForm.createTime = dayjs(this.addForm.createTime).format(
        'YYYY-MM-DD'
      )
      // const filteredList = this.factoryInventoryData.filter(item => item.purchaseNum !== 0 && item.warehousePosition);  //采购数量和库位必填
      const filteredList = this.factoryInventoryData.filter(
        (item) => item.singleNum !== 0
      ) //采购数量必填，库位非必填
      const selectedFieldsArray = filteredList.map((product) => ({
        materialId: product.materialId,
        productCode: product.productCode,
        productName: product.productName,
        singleNum: product.singleNum,
        norms: product.norms,
      }))

      if (this.optionType == 1) {
        const data = {
          ...this.addForm,
          singleProof: this.preSalesImg,
          list: selectedFieldsArray,
        }
        this.$api.singleAddSingle(data).then((res) => {
          if (res) {
            this.$message({ message: '新增成功', type: 'success' })
            this.addDialog = false
            this.getOutportList()
          }
        })
      } else if (this.optionType == 2) {
        const data = {
          ...this.addForm,
          singleProof: this.preSalesImg,
          list: selectedFieldsArray,
          singleNo: this.editSingleId,
        }
        this.$api.singleUpdateSingle(data).then((res) => {
          if (res) {
            this.$message({ message: '操作成功', type: 'success' })
            this.addDialog = false
            this.getOutportList()
          }
        })
      }
    },
    addProduct() {
      this.addDialog = true
      this.title = '新增出库单'
      this.disabled = false
      this.optionType = 1
      this.preSalesImg = this.$options.data.call(this).preSalesImg
      this.addForm = this.$options.data.call(this).addForm
      this.factoryInventoryData = []
    },
    handlePaste(event) {
      if (!(this.addDialog || this.outDialog)) return
      const clipboardData = event.clipboardData || window.clipboardData
      if (clipboardData) {
        for (let i = 0; i < clipboardData.items.length; i++) {
          const item = clipboardData.items[i]

          if (item.kind === 'file' && item.type.startsWith('image/')) {
            const file = item.getAsFile()
            if (file) {
              this.uploadImage(file)
            }
          } else {
            this.$message.error('请拷贝图片!')
            break
          }
        }
      }
    },
    uploadImage(imageFile) {
      const formData = new FormData()
      formData.append('file', imageFile)
      axios
        .post(`${this.$apiHost}/common/fileImgUrl`, formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
            token: store.state.token,
          },
        })
        .then((response) => {
          this.preSalesImg.push(response.data.result[0])
          // this.preSalesImgList.push('https://' + response.data.result[0]);
        })
        .catch((error) => {})
    },
    deletePic(i) {
      this.preSalesImg.splice(i, 1)
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.getOutportList()
    },
    handleCurrentChange(val) {
      this.pageNumber = val
      this.getOutportList()
    },
    reset() {
      this.pageSize = 20
      this.pageNumber = 1
      this.areaId = ''
      this.singleName = ''
      this.startTime = ''
      this.endTime = ''
      this.getOutportList()
    },
    editOutport(row) {
      this.title = '编辑'
      this.optionType = 2
      this.disabled = true
      this.addDialog = true
      this.editSingleId = row.singleNo
      this.addForm = {
        singleName: row.singleName,
        remark: row.remark,
        createTime: row.createTime,
        areaId: row.areaId,
      }
      if (row.singleProof) {
        row.singleProof.forEach((el) => {
          this.preSalesImgList.push(this.host + el)
        })
        this.preSalesImg = row.singleProof
      }
      this.$api
        .inventoryGetInventoryGoodsList({ areaId: row.areaId })
        .then((res) => {
          //将接口返回的产品数量替换成row的数量
          res.forEach((el) => {
            let match = row.list.find(
              (val) => val.productName === el.productName
            )
            if (match) {
              el.singleNum = match.singleNum
              // 标记替换的数据
              el.replaced = true
            } else {
              el.singleNum = 0
              //false为不标记
              el.replaced = false
            }
          })
          //将row.singleNum替换过的数据排在列表的前面
          res.sort((a, b) => b.replaced - a.replaced)
          this.factoryInventoryData = res
        })
    },
    countChange() {
      this.factoryInventoryData.forEach((el) => {
        if (!el.singleNum) {
          el.singleNum = 0
        }
      })
    },
    outportDetail(val) {
      this.positionDetail = true
      this.exportInfo = val
      this.$api
        .singleGetSingleListDetail({ singleNo: val.singleNo })
        .then((res) => {
          this.warehousePositionDetail = res
        })
    },
    exportDetail() {
      const wb = XLSX.utils.book_new()
      let data = [
        [this.exportInfo.singleName],
        [
          `仓库:${this.exportInfo.areaName}`,
          '',
          `创建人:${this.exportInfo.userName}`,
        ],
        [`售后原因:${this.exportInfo.remark}`],
        ['产品编码', '产品名称', '规格', '单位', '颜色', '数量'],
      ]
      this.warehousePositionDetail.map((el) => {
        data.push([
          el.productCode,
          el.productName,
          el.norms,
          el.unit,
          el.colour,
          el.count,
        ])
      })
      // data[data.length + 1] = [info.storeName,`实付:${info.totalDisCount}`,`补贴:${info.totalDiffPrice}`,`总价:${info.totalAmount}`];
      const ws = XLSX.utils.aoa_to_sheet(data)
      ws['!cols'] = [
        { wpx: 100 }, // 第一列宽度为250单位
        { wpx: 150 },
        { wpx: 150 }, // 第二列宽度为300单位
        { wpx: 100 }, // 第三列宽度为350单位
        { wpx: 100 },
        { wpx: 100 },
        { wpx: 100 },
      ]
      ws['A1'].s = {
        alignment: { horizontal: 'center' },
        font: { blod: true, color: { rgb: '000000' } },
        fill: { fgColor: { rgb: 'ff6a00' } },
      }
      ws['A1'].hpt = 140
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
      ws['!merges'] = [
        { s: { r: 0, c: 0 }, e: { r: 0, c: 6 } },
        { s: { r: 1, c: 0 }, e: { r: 1, c: 1 } },
        { s: { r: 1, c: 2 }, e: { r: 1, c: 6 } },
      ]
      const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' })
      // 创建一个 Blob 对象
      const blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' })
      // 使用 Blob 对象创建一个链接
      const link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      link.download = `${this.exportInfo.singleName}.xlsx`
      // 触发下载
      link.click()

      // 清理
      URL.revokeObjectURL(link.href)

      function s2ab(s) {
        const buf = new ArrayBuffer(s.length)
        const view = new Uint8Array(buf)
        for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xff
        return buf
      }
    },
  },
}
</script>
<style lang="less" scoped>
.title {
  display: flex;
  margin-left: 20px;

  span {
    display: flex;
    margin-top: 20px;
  }
}

.topSearch {
  width: 100%;
  height: 110px;
  box-shadow: inset 0 20px 10px rgba(0, 128, 255, 0.2);
  border-bottom: 1px solid rgba(0, 128, 255, 0.08);

  .search {
    display: flex;
    align-items: center;
    margin-top: 15px;

    span {
      margin-left: 20px;
    }
  }
}

.centerTable {
  margin-top: 20px;
}

.warehouseTag {
  display: flex;
  justify-content: center;
  height: 30px;
  //width: 120px;
  margin: 0 28px 0 28px;
  align-items: center;
  border-radius: 50px;
}

.warehouse_icon {
  width: 20px;
  height: 20px;
  margin-right: 3px;
}

/deep/ .el-dialog__header {
  background-color: #0f79e2;
  //border-top-left-radius: 20px;
  //border-top-right-radius: 20px;
}

/deep/ .el-dialog__title {
  color: #fff;
}

/deep/ .center {
  border-radius: 20px;
}

/deep/ .el-dialog__headerbtn .el-dialog__close {
  color: #fff;
}
</style>
